<template>
  <el-dialog
    v-dialogDrag
    :visible="isDialogVisible"
    :title="titleName"
    width="70%"
    center
    :append-to-body="true"
    :close-on-click-modal="false"
    @close="closeEdit"
  >
    <dialogHeader slot="title" :title="titleName" :style-type="$store.state.app.dialogType" />
    <div class="filter-container filter-params">
      <one-table-template
        ref="multipleTable"
        :dynamic-api-config="apiConfig"
        :dynamic-buttons="dynamicButtons"
        :dynamic-components="tableComponents"
        :dynamic-table-cols="dynamicTableCols"
        :dynamic-form-fields="formField"
        :dynamic-is-show-more-btn="true"
        :dynamic-is-show-select="true"
        :dynamic-export-converts="dynamicExportConverts"
        :refresh-table-key="refreshTableKey"
      />
    </div>
  </el-dialog>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
export default {
  components: {
    dialogHeader,
    OneTableTemplate
  },
  props: {
    isDialogVisible: {
      type: Boolean,
      default: false
    },
    dataForForm: {
      type: Object,
      default: () => {}
    },
    titleName: {
      type: String,
      default: ''
    },
    editData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      ord: '',
      carSeriesId: '', // 车系ID
      updateControlId: '', //  并发控制id
      refreshTableKey: '0',
      editPopupsState: 'add',
      // table表格查询API配置对象
      apiConfig: {
        ServiceCode: 'queryCarTypeById',
        APIUrl: '/mp/e3sh/vesale/basics/carTypeService/queryCarTypeById.do'
      },
      // 动态组件-查询条件  车型维护
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '车系编码：',
              codeField: 'carSeriesCode',
              isRequire: true,
              disabled: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey2',
              labelName: '车系名称：',
              codeField: 'carSeriesCN',
              isRequire: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey3',
              labelName: '车系英文名：',
              codeField: 'carSeriesEN',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey4',
              labelName: '排列顺序：',
              codeField: 'ordeNo',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey5',
              labelName: '状态：',
              codeField: 'isEnableCode',
              isRequire: true,
              component: () => import('@/components/org/isEnable/isEnableOne'),
              type: 'dropdownList',
              isMust: true,
              span: 8
            }
          ],
      // form 的表单对象
      formField: this.$utils.getFormField(
        this,
        {
          carSeriesCode: '', // 车系编码
          carSeriesCN: '', // 车系名称
          carSeriesEN: '', // 英文名称
          ordeNo: '', // 排列顺序
          isEnableCode: '1', // 状态
          carSeriesId: this.carSeriesId,
          updateControlId: this.updateControlId
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
      // 动态组件-按钮
      dynamicButtons:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          : [
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              name: 'search',
              clickEvent: () => this.save(),
              text: '保存'
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              icon: 'iconfont  icon-cancel',
              clickEvent: () => this.closeEdit(1),
              text: '取消'
            }
          ],
      // 动态组件-表格网格列
      dynamicTableCols:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length >
          0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
          : [],
      // 字段格式化转换（用于导出excel）（kvs表示键值转换）
      dynamicExportConverts: {
        isEnable: {
          convert: 'kvs',
          kvs: {
            '1': '是',
            '0': '否'
          }
        }
      },
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.handleSelectionChange(selection)
        }
      }
    }
  },
  // watch: {
  //   'formField.ordeNo'(nVal, old) {
  //     if (nVal !== this.ord) {
  //       let lists = []
  //       lists = this.$parent.$refs.multipleTable.list
  //       const arr = []
  //       for (const i of lists) {
  //         arr.push(i.ordeNo)
  //         console.log(arr.includes(this.formField.ordeNo))
  //         if (!arr.includes(this.formField.ordeNo)) {
  //           return this.$message({ message: '排列顺序重复', duration: 2000 })
  //         }
  //       }
  //     }
  //   }
  // },
  mounted() {
    // 数据回填
    const data = JSON.parse(JSON.stringify(this.editData))
    data.isEnableCode === '停用' ? (data.isEnableCode = '0') : (data.isEnableCode = '1')
    this.formField = data
    this.carSeriesId = data.carSeriesId
    this.updateControlId = data.updateControlId
    this.ord = data.ordeNo
  },
  methods: {
    // form表单组件每个元素所占栅格栏数每行24格
    spanNum() {
      return 24
    },

    // 关闭弹窗
    closeEdit(type) {
      this.$emit('closeEdit', type)
    },

    // 保存
    save() {
      this.$utils.validataMoth(this, 'validpage')
      if (this.valid) {
        const that = this
        const returnObj = {
          apiConfig: {
            ServiceCode: 'editCarTypeById',
            APIUrl: '/mp/e3sh/vesale/basics/carTypeService/editCarTypeById.do'
          },
          variables: this.formField
        }
        var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
        this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
          if (response.result === '0') {
            this.$refs['multipleTable'].listLoading = false
            if (response.msg) {
              this.$message({ message: response.msg, type: 'warn', duration: 2000 })
            // that.closeEdit(1)
            }
            return
          } else {
            that.$refs['multipleTable'].listLoading = false
            that.$message({
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            that.closeEdit(2)
          }
        }).catch(err => {
          console.info(err)
        })
      }
    }
  }
}
</script>
